﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using MODEL;
using MySql.Data.MySqlClient;
using Common;

namespace DAL
{
    public class AgricultureDAL
    {
        public static Task<IEnumerable<AgricultureInfo>> QueryAgricultureInfosAsync(AgricultureQueryCriteria criteria)
        {
            AgricultureQueryCriteria queryCriteria = criteria == null ? new AgricultureQueryCriteria() : criteria;

            string sql = @"SELECT userName as UserName
                        , materialsName as MaterialsName
                        , factory as Factory
                        , factoryAddress as FactoryAddress
                        , productionDate as DeadLine
                        , usefulDate as UsefulDeadLine
                        , productionPlace as ProductionPlace
                        , phoneNum as PhoneNum
                        from msap_db.agri_materials
                        WHERE
                        (@SearchName is null OR materialsName = @SearchName)
                        AND(@SearchFactory is null OR factory = @SearchFactory)
                        AND(@SearchTime is null OR productionDate = @SearchTime)";

            using (MySqlConnection conn = new MySqlConnection(AppSetting.Instance.MySqlConnectionStr))
            {
                return conn.QueryAsync<AgricultureInfo>(sql, new
                {
                    SearchName = queryCriteria.SearchName.ChangeEmptyToNull(),
                    SearchFactory = queryCriteria.SearchFactory.ChangeEmptyToNull(),
                    SearchTime = queryCriteria.SearchTime.ChangeEmptyToNull()
                });
            }
        }
    }
}
